package chProtocol;

import common.Payload;

public class Packet {
    public static final byte MESSAGE_STX = (byte) 0xFE;

    public final int len;

    public int type;

    public Payload payload;

    public int fcs;

    public Packet(int payloadLength) {
        len = payloadLength;
        payload = new Payload(payloadLength);
    }

    public boolean payloadIsFilled() {
        return payload.size() >= len;
    }

    public byte generateCRC() {
        byte result =  (byte)type;
        payload.resetIndex();
        final int payloadSize = payload.size();
        for (int i = 0; i < payloadSize; i++) {
            result += payload.getByte();
        }
        fcs = result;
        return result;
    }

    public void toBytes(byte[] bytes) {
        bytes[0] = (byte) 0xfe;
        bytes[1] = (byte) (len + 1);
        bytes[2] = (byte) type;

        payload.resetIndex();
        final int payloadSize = payload.size();
        for (int i = 0; i < payloadSize; i++) {
            bytes[i + 3] = payload.getByte();
        }
        bytes[payloadSize + 3] = (byte) fcs;
    }
}
